<template>
  <div class="detailsWrap productWrap">
    <div>
      <div class="topic">
          <h1 class="detailsTitle">
            编辑规则
            <span class="icon-wrap" @click="rulesVisible = true">
                <iot-icon type="icon-basic-edit" style="color: #2F54EB; font-size: 16px;" ></iot-icon>
            </span>
          </h1>
          <expandComp :expand="expand" @toggleExpand="toggleExpand"></expandComp>
      </div>
      <div class="primary-info">
          <div class="primary-info-item" v-for="(item, index) of primaryList" :key="index">
              <div class="icon-wrap" :style="item.style">
                  <iot-icon :type="item.icon" :style="{color: '#ffffff', fontSize: '24px'}"></iot-icon>
              </div>
              <div class="attr-val">
                  <h1 v-if="item.key === 'level'">{{ item.value | warningLevelFilter }}</h1>
                  <h1 v-else-if="item.key === 'type'">{{ item.value === 1 ? "设备告警" : "" }}</h1>
                  <h1 v-else>{{ item.value }}</h1>
                  <p>{{ item.name }}</p>
              </div>
          </div>
      </div>
      <div class="detailsList" :style="{display: expand ? 'block' : 'none'}">
        <p class="rulesTitle">规则描述</p>
        <p>{{ ruleDetails.remark }}</p>
      </div>
      <div class="split-pie"></div>
    </div>
    <div>
      <div class="rulesCon">
        <h1>规则内容</h1>
        <div @click="rulesDialog = true">
          <iot-icon type="icon-basic-edit" style="color: #191B27; font-size: 14px;" ></iot-icon>
          <span class="icon-desc">编辑触发规则</span>
        </div>
      </div>
      <div class="rule-content">
        <ul v-if="ruleInfo.conditions && ruleInfo.conditions.length > 0">
          <li>
            <p class="tableTitle">
              <span class="tableItem" style="text-align: left; border: none"
                >触发条件</span
              >
              <span class="limit-condition">
                限制：{{
                  ruleInfo.perfectMatchMode === 0
                    ? "满足任意条件执行"
                    : "满足全部条件执行"
                }}
              </span>
            </p>
            <p
              v-for="(item, index) in ruleInfo.conditions"
              :key="item.id"
              class="tableList"
            >
              <span class="tableItem">条件{{ index + 1 }}</span>
              <span style="padding-left: 20px">{{
                item.conditionContent
              }}</span>
            </p>
          </li>
          <div class="rulesCon">
            <h1></h1>
            <div @click="actionDialog = true">
              <iot-icon type="icon-basic-edit" style="color: #191B27; font-size: 14px;" ></iot-icon>
              <span class="icon-desc">编辑动作规则</span>
            </div>
          </div>
          <li>
            <p class="tableTitle">
              <span class="tableItem" style="text-align: left; border: none;">动作</span>
              <span class="limit-condition">
                执行方式：{{
                  actionForm.actionExecutionMode === 'serial'
                    ? "串行"
                    : "并行"
                }}
              </span>
            </p>
            <div
              v-for="(item, index) in showNoticeList"
              :key="index"
              class="tableList"
            >
              <span class="tableItem">动作{{ index + 1 }}</span>
              <div>
                <span style="padding: 0 20px">{{ item.name }}</span>
                <span>{{ item.value }}</span>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <a-modal
      :width="800"
      title="编辑规则"
      :visible="rulesVisible"
      ok-text="确认"
      cancel-text="取消"
      @ok="onSure"
      @cancel="rulesVisible = false"
    >
      <a-form-model ref="ruleForm" :model="form" :rules="ruleFormRules">
        <a-form-model-item label="规则名称" prop="name">
          <a-input
            v-model="form.name"
            placeholder="1-32位字符，支持中文，英文，数字及特殊字符"
          />
        </a-form-model-item>
        <a-form-model-item label="告警类型" prop="type">
          <a-radio checked>
            设备告警
          </a-radio>
        </a-form-model-item>
        <a-form-model-item label="告警级别" prop="level">
          <search-select
            v-model="form.level"
            placeholder="请选择告警级别"
            :options="typeList"
          >
          </search-select>
        </a-form-model-item>
        <a-form-model-item label="规则描述" prop="desc">
          <a-textarea class="ant-textarea" v-model="form.desc" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 编辑规则弹窗 -->
    <a-modal
      :width="1100"
      title="编辑触发规则"
      :visible="rulesDialog"
      ok-text="确认"
      cancel-text="取消"
      :okButtonProps="{props: {loading: loadingBtn}}"
      @ok="onSubmit"
      @cancel="rulesDialog = false"
    >
      <a-form-model
        ref="ruleForm"
        class="editDialog"
        :colon="false"
        :model="rulesForm"
        :rules="rules"
      >
        <a-form-model-item label="静默时间" prop="time">
          <span class="timeDes"
            >若已配置静默时间，则告警规则触发告警后，在设定的时间范围内将不再重复生成告警和通知。超出设定时间告警仍未恢复，则会再次触发告警。</span
          >
          <a-input
            v-model="rulesForm.time"
            placeholder="请输入静默时间"
            addon-after="秒"
          />
        </a-form-model-item>

        <a-form-model-item label="执行限制" prop="perfectMatchMode">
          <a-radio-group v-model="rulesForm.perfectMatchMode">
            <a-radio value="0"> 满足任意条件执行 </a-radio>
            <a-radio value="1"> 满足全部条件执行 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <div
          v-for="(item, index) in rulesForm.rules"
          :key="item.keyId"
          class="rulesWrap"
        >
          <h1 class="page-title">
            启动规则
            <a-tooltip placement="top" v-if="rulesForm.rules.length > 1">
              <template slot="title">
                删除
              </template>
              <a-icon
                type="close"
                class="delete-card"
                @click="deleteRule(index)"
              ></a-icon>
            </a-tooltip>
          </h1>
          <a-form-model-item
            label="设备"
            :prop="`rules.${index}.product`"
            :rules="{
              required: true,
              message: '请选择设备',
              trigger: 'change',
            }"
          >
            <search-select
              v-model="item.product"
              placeholder="请选择设备"
              :options="productList"
              @change="productChange(item)"
            >
            </search-select>
          </a-form-model-item>
          <div
            class="rule-wrap"
            v-for="(node, count) in item.conditionContentView"
            :key="count">
            <div class="rulesList">
              <a-form-model-item
                label="触发方式"
                :prop="`rules.${index}.conditionContentView.${count}.type`"
                :rules="{
                  required: true,
                  message: '请选择触发方式',
                  trigger: 'change',
                }"
              >
                <search-select
                  v-model="node.type"
                  placeholder="请选择触发方式"
                  :options="item.triggerTypeList"
                  @change="triggerChange(node)"
                >
                </search-select>
              </a-form-model-item>
              <a-form-model-item
                label="功能"
                :prop="`rules.${index}.conditionContentView.${count}.fun`"
                :rules="{
                  required: true,
                  message: '请选择功能',
                  trigger: 'change',
                }"
              >
                <search-select
                  v-model="node.fun"
                  placeholder="请选择功能"
                  :options="item.triggerTypeList.find(item => item.value === node.type)
                    ? item.triggerTypeList.find(item => item.value === node.type).triggerArr
                    : []"
                >
                </search-select>
              </a-form-model-item>
              <a-form-model-item
                  label="判断条件"
                  :prop="`rules.${index}.conditionContentView.${count}.condition`"
                  :rules="{
                    required: true,
                    message: '请选择判断条件',
                    trigger: 'change',
                  }"
                >
                <search-select
                  v-model="node.condition"
                  placeholder="请选择判断条件"
                  :options="conditionList"
                >
                </search-select>
                </a-form-model-item>
                <a-form-model-item
                  label="预设值"
                  :prop="`rules.${index}.conditionContentView.${count}.val`"
                  :rules="{
                    required: true,
                    message: '请选择预设值',
                    trigger: 'change',
                  }"
                >
                  <a-input
                    v-model="node.val"
                    placeholder="请输入预设值"
                  />
                </a-form-model-item>
                <a-form-model-item
                  label=" ">
                  <a-radio-group v-model="node.con" button-style="solid">
                    <a-radio-button value="or">
                      OR
                    </a-radio-button>
                    <a-radio-button value="and">
                      AND
                    </a-radio-button>
                  </a-radio-group>
                  <!-- <a-select
                    v-model="node.con"
                    placeholder="组装方式"
                    style="width: 120px; margin: 0 30px 0 120px"
                    @change="
                      onConnect(node.isStyle, index, count, node.con)
                    "
                  >
                    <a-select-option value="and"> and </a-select-option>
                    <a-select-option value="or"> or </a-select-option>
                  </a-select> -->
                </a-form-model-item>
                <a-form-model-item>
                  <a-tooltip placement="top">
                    <template slot="title">
                      删除
                    </template>
                    <a-icon
                      type="close"
                      class="delete-card"
                      v-if="item.conditionContentView.length > 1"
                      @click="deleteCard(item.keyId, node.cardId)"
                    ></a-icon>
                  </a-tooltip>
                </a-form-model-item>
            </div>
          </div>
          <a-button class="add-rule" @click="onConnect(index)">
            <a-icon type="plus" />
            添加条件
          </a-button>
          <p class="condition-exp">if "{{ item.expression }}"</p>
        </div>
        <a-button class="hollow-btn" @click="addRules">
          <a-icon type="plus" />
          增加启动规则
        </a-button>
      </a-form-model>
    </a-modal>
    <!-- action modal -->
    <a-modal
      :width="1100"
      title="编辑动作内容"
      :visible="actionDialog"
      ok-text="确认"
      cancel-text="取消"
      :okButtonProps="{props: {loading: loadingBtn2}}"
      @ok="saveActionHandle"
      @cancel="actionDialog = false">
      <a-form-model
        ref="actionForm"
        :colon="false"
        :model="actionForm"
      >
        <a-form-model-item label="执行方式" prop="actionExecutionMode">
          <a-radio-group v-model="actionForm.actionExecutionMode">
            <a-radio value="serial"> 串行 </a-radio>
            <a-radio value="parallel"> 并行 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <div class="action-container" v-for="(item, index) of actionForm.actionReqs" :key="index">
          <a-form-model-item style="position: relative;" label="执行动作" :prop="`actionReqs.${index}.actionTypeName`"
            :rules="[{required: true, message: '请选择执行动作', trigger: 'change'}]">
            <a-radio-group
              class="notice-check"
              v-model="item.actionTypeName"
              >
              <div class="notice-item">
                  <a-radio value="alarm">告警中心</a-radio>
              </div>
              <div class="notice-item">
                <a-radio value="sms">短信通知</a-radio>
                <a-form-model-item
                  v-if="item.actionTypeName === 'sms'"
                  :prop="`actionReqs.${index}.sms`"
                  :rules="[
                    {validator: validatePhone, trigger: 'blur'}
                  ]">
                  <a-input
                    v-model="item.sms"
                    placeholder="请输入手机号，多个手机号请使用','分开"
                  />
                </a-form-model-item>
              </div>
              <div class="notice-item">
                <a-radio value="email">邮件通知</a-radio>
                <a-form-model-item
                  v-if="item.actionTypeName === 'email'"
                  :prop="`actionReqs.${index}.email`"
                  :rules="[
                    {validator: validateEmail, trigger: 'blur'}
                  ]"
                  >
                  <a-input
                    v-model="item.email"
                    placeholder="请输入邮箱地址，多个地址请使用','分开"
                  />
                </a-form-model-item>
              </div>
              <div class="notice-item">
                <a-radio value="http">第三方推送</a-radio>
                <div v-if="item.actionTypeName === 'http'" style="display: flex;">
                  <a-form-model-item
                    style="width: 32%; margin-bottom: 0;"
                    :prop="`actionReqs.${index}.http.url`"
                    :rules="[
                      {required: true, message: '请输入URL', trigger: 'blur'}
                    ]"
                    >
                    <a-input
                      v-model="item.http.url"
                      placeholder="请输入接口地址"
                    />
                  </a-form-model-item>
                  <a-form-model-item style="margin: 0 2%; width: 32%">
                    <a-input
                      v-model="item.http.header"
                      placeholder="请输入请求头"
                    />
                  </a-form-model-item>
                  <a-form-model-item
                    style="width: 32%"
                    :prop="`actionReqs.${index}.http.method`"
                    :rules="[
                      {required: true, message: '请输入请求方式', trigger: 'blur'}
                    ]">
                    <a-input
                      v-model="item.http.method"
                      placeholder="请输入请求方式"
                    />
                  </a-form-model-item>
                </div>
              </div>
              <div class="notice-item">
                <a-radio value="cmddown">指令下发</a-radio>
                <div v-if="item.actionTypeName === 'cmddown'">
                  <search-select
                    v-model="item.productCode"
                    labelName="产品"
                    width="100%"
                    :options="deviceClassify"
                    @change="getDevicesAndServices(item.productCode, index)"
                  ></search-select>
                  <search-select
                    v-model="item.deviceCodes"
                    labelName="设备"
                    width="100%"
                    showArrow
                    mode="multiple"
                    :options="deviceList[item.productCode]"
                  ></search-select>
                  <a-form-model-item
                    style="margin-bottom: 0;"
                    :prop="`actionReqs.${index}.services`"
                    :rules="[
                      {required: true, message: '请选择服务类型', trigger: 'change'}
                    ]">
                  <search-select
                    v-model="item.services"
                    labelName="服务类型"
                    width="100%"
                    :options="servicesList[item.productCode]"
                    @change="getInputParams(item.services, item.productCode, index)"
                  ></search-select>
                  </a-form-model-item>
                  <div v-if="inputData.length > 0">
                    <div class="attr-wrap" v-for="inputItem of inputData[index]">
                      <a-input
                        class="expose-input"
                        v-model="inputItem.value"
                        :key="inputItem.identifier"
                        :addon-before="inputItem.name"
                        :addon-after="inputItem.dataType.specs.unit">
                      </a-input>
                    </div>
                  </div>
                </div>
              </div>
            </a-radio-group>
            <a-tooltip
              style=" position: absolute; right: 0; top: -20px; "
              placement="top" v-if="actionForm.actionReqs.length > 1">
              <template slot="title">
                删除
              </template>
              <a-icon
                type="close"
                class="delete-card"
                @click="deleteAction(index)"
              ></a-icon>
            </a-tooltip>
          </a-form-model-item>
        </div>
        <a-button style="margin-top: 16px;" class="hollow-btn" @click="addActions">
          <a-icon type="plus" />
          增加执行动作
        </a-button>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { getDeviceData } from "@/api/equipGroup";
import { getProductList, newActionRuleAPI, productDetail, productList } from "@/api/product";
import {
    editRules,
    editRulesContent,
    getRulesContent,
    getWarningRulesDetails,
} from "@/api/warningCenter";
import expandComp from '@/components/expand.vue';
import { phoneCheck2, validateEmail, validateNum } from "@/utils/validate";
import { cloneDeep } from "lodash-es";


const typeList = [
  {
    label: '紧急',
    value: '2'
  },
  {
    label: '严重',
    value: '1'
  },
  {
    label: '普通',
    value: '0'
  },
]
const conditionList = [
  {
    label: '>',
    value: '>'
  },
  {
    label: '<',
    value: '<'
  },
  {
    label: '>=',
    value: '>='
  },
  {
    label: '<=',
    value: '<='
  },
  {
    label: '=',
    value: '=='
  },
  {
    label: '!=',
    value: '!='
  },
]
const plainOptions = [
  'alarm',
  'sms',
  'email',
  'http'
]
const keysObj = {
  events: "设备事件触发",
  properties: "设备属性触发",
  services: "设备服务触发"
}
const keysArr = Object.keys(keysObj)

const alarmMapObj = {
  alarm: '告警中心',
  sms: '短信通知',
  email: '邮件通知',
  http: '第三方推送',
  cmddown: '指令下发'
}
export default {
  name: "EditRules",
  components: {
    expandComp
  },
  data() {
    return {
      rulesVisible: false,
      typeList,
      conditionList,
      loadingBtn: false,
      loadingBtn2: false,
      // action
      deviceClassify: [],
      deviceList: {},
      servicesList: {},
      inputData: [],
      actionDialog: false,
      actionForm: {
        actionExecutionMode: 'serial',
        actionReqs: [
          {
            actionTypeName: '',
            sms: '',
            email: '',
            productCode: '',
            deviceCodes: [],
            services: '',
            http: {
              url: '',
              method: '',
              header: ''
            }
          }
        ],
      },
      ruleConfigureId: '',
      validatePhone: phoneCheck2,
      validateEmail,
      // 当前告警规则id
      id: "",
      ruleId: "",
      ruleDetails: {},
      expand: true,
      // 当前规则是否为编辑状态
      visible: true,
      // 编辑规则弹窗是否显示
      rulesDialog: false,
      // 当前规则编辑表单数据
      form: {},
      primaryList: [],
      ruleFormRules: {
        name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
        level: [
          { required: true, message: "请选择告警级别", trigger: "change" },
        ],
      },
      // 编辑规则内容表单数据
      rulesForm: {
        time: "",
        // notice: [],
        sms: {
          smsAddress: "",
          templateCode: "",
        },
        email: {
          emailAddress: "",
          templateCode: "",
        },
        http: {
          url: "",
          header: {
            token: "",
          },
          method: "",
        },
        perfectMatchMode: "",
        rules: [
          {
            keyId: 1,
            product: undefined,
            triggerTypeList: [],
            conditionType: "expression",
            expression: "",
            conditionContentView: [
              {
                cardId: 1,
                type: "",
                fun: "",
                condition: "",
                val: "",
                con: 'or'
              },
            ],
          },
        ],
      },
      // 编辑规则内容弹窗中的产品列表数据
      productList: [],
      // 编辑规则内容表单验证规则
      rules: {
        time: [
          { required: true, message: "请输入静默时间", trigger: "blur" },
          { validator: validateNum, trigger: "blur" },
        ],
        // notice: [
        //   { required: true, message: "请选择通知方式", trigger: "change" },
        // ],
        perfectMatchMode: [
          { required: true, message: "请选择执行限制", trigger: "change" },
        ]
      },
      ruleInfo: {},
      showNoticeList: []
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.getProductList()
    this.getRulesDetails(true);
    productList()
      .then((res) => {
        this.productList = res.data.map(item => {
          item.label = item.productName
          item.value = item.code
          return item
        });
      })
      .catch((error) => {
        console.log(error);
      });
  },
  computed: {
    //修改规则所需参数
    getParams() {
      const params = {
        id: this.ruleId,
        perfectMatchMode: this.rulesForm.perfectMatchMode,
        silencePeriod: this.rulesForm.time,
        alarmRuleInfoId: this.id,
        conditionReqs: [],
      };
      params.conditionReqs = this.rulesForm.rules.map((item) => {
        const condition = {
          productCode: item.product,
          conditionType: item.conditionType,
          conditionContent: item.expression,
          conditionContentView: "",
        };
        return condition;
      });
      return params;
    },
  },
  watch: {
    ruleDetails: {
      handler: function(val) {
        this.primaryList = [
          {
            name: '规则名称',
            icon: 'icon-add-rule',
            key: 'alarmRuleName',
            value: val.alarmRuleName
          },
          {
            name: '告警级别',
            icon: 'icon-grade',
            key: 'level',
            value: val.level,
            style: {
              background: '#92DEE6',
            }
          },
          {
            name: '告警类型',
            icon: 'icon-iotdata',
            key: 'type',
            value: val.type
          },
        ]
      },
      deep: true,
      immediate: true
    },
    rulesForm: {
      handler() {
        this.rulesForm.rules.forEach((item) => {
          let expression = "";
          let len = item.conditionContentView.length
          item.conditionContentView.forEach((_item, _index) => {
            expression += `${_item.type}.${_item.fun}${_item.condition}${_item.val}`;
            if (_index !== len - 1) {
              expression += ` ${_item.con} `;
            }
          });
          item.expression = expression;
        });
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    toggleExpand(expand) {
      this.expand = expand
    },
    // 产品
    getProductList() {
      getProductList(1, 100).then(res => {
        this.deviceClassify = res.data.records.map(item => {
          Object.assign(this.deviceList, {[item.code]: []})
          Object.assign(this.servicesList, {[item.code]: []})
          return {
            label: item.productName,
            value: item.code,
            id: item.id
          }
        })
      })
    },
    // 设备列表
    async getDevicesAndServices(productCode, index, isEcho = false) {
      if (!isEcho) {
        this.actionForm.actionReqs[index].deviceCodes = []
        this.actionForm.actionReqs[index].services = ''
        this.inputData.splice(index, 1)
      }
      if (!this.deviceList[productCode].length) {
        await getDeviceData({
          page: 1,
          pageSize: 100,
          productCode,
        }).then(res => {
          let result =  res.data.records.map(item => {
            return {
              label: item.code,
              value: item.code
            }
          })
          Object.assign(this.deviceList, {[productCode]: result})
          this.$forceUpdate()
        })
      }
      if (!this.servicesList[productCode].length) {
        let result = this.deviceClassify.find(item => {
          return item.value === productCode
        })
        if (result) {
          let id = result.id
          await productDetail(id).then(res => {
            let services = JSON.parse(res.data.metaData).services
            let result = services.map(item => {
              return {
                label: item.name,
                value: item.identifier,
                total: item
              }
            })
            Object.assign(this.servicesList, {[productCode]: result})
            this.$forceUpdate()
          })
        }
      }
    },
    getInputParams(service, productCode, index) {
      let result = this.servicesList[productCode].find(item => {
        return item.value === service
      })
      if (result) {
        let inputData = result.total.inputData.map(item => {
          item.value = ''
          return item
        })
        this.$set(this.inputData, index, cloneDeep(inputData))
      } else {
        this.$set(this.inputData, index, [])
      }
    },
    saveActionHandle() {
      this.$refs.actionForm.validate((valid) => {
        if (valid) {
          this.loadingBtn2 = true
          let actionReqs = this.actionForm.actionReqs.map((item, index) => {

            let param = null
            if (item.actionTypeName === 'alarm') {
              param = {}
            } else if (item.actionTypeName === 'sms') {
              param = {
                smsAddress: item.sms.split(','),
                templateCode: "001"
              }
            } else if (item.actionTypeName === 'email') {
              param = {
                emailAddress: item.email.split(','),
                templateCode: "001"
              }
            } else if (item.actionTypeName === 'http') {
              param = {
                url: item.http.url,
                header: item.http.header,
                method: item.http.method,
              }
            } else if (item.actionTypeName === 'cmddown') {
              let serviceName = this.servicesList[item.productCode].find(serviceItem => serviceItem.value === item.services).label

              let inputParam = {}
              this.inputData[index].forEach(item => {
                if (item.value) {
                  inputParam[item.identifier] = item.value
                }
              })
              param = {
                identifier: item.services,
                inputParam,
                deviceCodes: item.deviceCodes,
                productCode: item.productCode,
                serviceName
              }
            }
            return {
              actionTypeName: item.actionTypeName,
              orderIndex: index,
              param
            }
          })
          let submitData = {
            actionExecutionMode: this.actionForm.actionExecutionMode,
            actionReqs,
            ruleConfigureId: this.ruleId
          }
          newActionRuleAPI(submitData).then((res) => {
            this.$message.success("编辑成功！")
            this.actionDialog = false
            this.loadingBtn2 = false
            this.getActions(res.data.actionReqs)
          }).catch(err => {
            this.loadingBtn2 = false
          });
        } else {
          console.log("error submit!!");
        }
      });
    },
    triggerChange(node) {
      node.fun = undefined
    },
    // 获取告警规则详情
    getRulesDetails(flag = false) {
      getWarningRulesDetails(this.id)
        .then((res) => {
          let info = res.data;
          this.ruleDetails = info;
          this.ruleId = res.data.ruleId
          this.form = {
            name: info.alarmRuleName,
            level: info.level.toString(),
            desc: info.remark,
          };
          if (flag && this.ruleId) {
            this.getRulesData();
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 确认编辑操作
    onSure() {
      let info = this.form;
      editRules(info.name, info.level, info.desc, 1, this.id)
        .then(() => {
          this.getRulesDetails();
          this.$message.success("编辑成功！");
          this.rulesVisible = false;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 获取规则内容数据
    getRulesData() {
      getRulesContent(this.ruleId)
        .then((res) => {
          let info = JSON.parse(JSON.stringify(res.data));
          let resRules = JSON.parse(JSON.stringify(this.rulesForm));
          //静默时间
          resRules.time = info.silencePeriod;
          // 处理通知方式
          this.getActions(info.actions)
          /*  处理规则集合  */
          //执行限制
          if (info.conditions.length > 0) {
            resRules.rules.length = 0;
            info.conditions.forEach(async (item, index) => {
              const ruleObj = {
                keyId: index + 1,
              };
              //获取条件类型
              ruleObj.conditionType = item.conditionType;
              //获取产品名称
              const productListRes = await productList();
              const product = productListRes.data.find(
                (product) => product.code === item.productCode
              );
              if (!product) return
              ruleObj.product = product.code;
              const productDataRes = await productDetail(product.id);
              const productData = JSON.parse(productDataRes.data.metaData);
              //处理触发方式列表
              ruleObj.triggerTypeList = this.dealTriggerTypeList(productData);
              //将条件表达式转化为数组用于展示
              const { ruleArr } = this.stringToArray(
                item.conditionContent
              );
              ruleObj.conditionContentView = ruleArr.map((rule, ruleIndex) => {
                return {
                  cardId: ruleIndex + 1,
                  type: rule.trigger,
                  fun: rule.type,
                  condition: rule.symbol,
                  val: rule.value,
                  con: rule.logic,
                };
              });
              //最后一条规则的逻辑符号置为undfind
              ruleObj.conditionContentView[
                ruleObj.conditionContentView.length - 1
              ].con = 'or';
              resRules.rules.push(ruleObj);
            });
          }
          resRules.perfectMatchMode = info.perfectMatchMode.toString();
          this.rulesForm = Object.assign(this.rulesForm, resRules);
          this.ruleInfo = res.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getActions(actions) {
      console.log(actions)
      this.showNoticeList = []
      let inputValue = []
      let actionsResult = actions.map((item, index) => {
        let result = {
          actionTypeName: item.actionTypeName,
          sms: '',
          email: '',
          productCode: '',
          deviceCodes: [],
          services: '',
          http: {
            url: '',
            method: '',
            header: ''
          }
        }
        let param = JSON.parse(item.param)
        const action = {
          name: alarmMapObj[item.actionTypeName],
          value: "",
        };
        if (item.actionTypeName === "email") {
          let email = param.emailAddress.join(",");
          result.email = email
          action.value = email
        }  else if (item.actionTypeName === "sms") {
          let sms = param.smsAddress.join(",");
          result.sms = sms
          action.value = sms;
        } else if (item.actionTypeName === "http") {
          result.http.url = param.url;
          result.http.header = param.header;
          result.http.method = param.method;
          action.value = `url: ${param.url}, header: ${param.header}, method: ${param.method}`;
        } else if (item.actionTypeName === 'cmddown') {
          result.productCode =  param.productCode
          result.deviceCodes = param.deviceCodes
          result.services = param.identifier
          action.value = item.param
        }
        if (item.actionTypeName === 'cmddown') {
          inputValue.push(param.inputParam)
        } else {
          inputValue.push([])
        }
        this.showNoticeList.push(action)
        return result
      });
      if (actionsResult) {
        this.actionForm.actionReqs = actionsResult
      }
      actionsResult.forEach(async (item, index) => {
        if (item.actionTypeName === 'cmddown') {
          await this.getDevicesAndServices(item.productCode, index, true)
          this.getInputParams(item.services, item.productCode, index)
          this.inputData[index].forEach((inputItem) => {
            inputItem.value = inputValue[index][inputItem.identifier] || ''
          })
        }
      })
    },
    //将条件表达式转化为数组用于展示
    stringToArray(data) {
      let ruleArr = [];
      if (data.indexOf(" and ") > -1 || data.indexOf(" or ") > -1) {
        ruleArr = this.dealLogic(data)
      } else {
        const symbolArr = ["<=", ">=", "==", "!=", ">", "<"];
        const symbol = symbolArr.find((symbol) => data.indexOf(symbol) !== -1);
        ruleArr.push({
          trigger: data.split(symbol)[0].split(".")[0],
          type: data.split(symbol)[0].split(".")[1],
          value: data.split(symbol)[1],
          symbol,
          logic: 'or',
        });
      }
      return { ruleArr };
    },
    //根据逻辑符号处理条件表达式
    dealLogic(data) {
      let ruleArr = [];
      let arr1 = data.split(/(\s*and\s*|\s*or\s*)/);
      const symbolArr = ["<=",  ">=", "==", "!=", ">", "<"];
      arr1.forEach((item, index) => {
        if (item.indexOf('or') > -1 || item.indexOf('and') > -1) return
        const symbol = symbolArr.find((symbol) => item.indexOf(symbol) !== -1);
        ruleArr.push({
          trigger: item.split(symbol)[0].split(".")[0],
          type: item.split(symbol)[0].split(".")[1],
          value: item.split(symbol)[1],
          symbol,
          logic: arr1[index + 1] ? arr1[index + 1].replace(/(^\s*)|(\s*$)/g, "") : 'or'
        });
      });
      return ruleArr;
    },
    //处理触发方式列表的方法
    dealTriggerTypeList(productData) {
      const triggerTypeList = [];

      for (let key in productData) {
        if (keysArr.includes(key)) {
          let result = productData[key].map(item => {
            return {
              label: item.name,
              value: item.identifier
            }
          })
          if (result && result.length > 0) {
            triggerTypeList.push({
              label: keysObj[key],
              value: key,
              triggerArr: result,
            })
          }
        }
      }
      return triggerTypeList;
    },
    addActions() {
      this.actionForm.actionReqs.push({
        actionTypeName: '',
        sms: '',
        email: '',
        productCode: '',
        deviceCodes: [],
        services: '',
        http: {
          url: '',
          method: '',
          header: ''
        }
      });
    },
    // 点击编辑规则弹窗中的增加启动规则按钮
    addRules() {
      this.rulesForm.rules.push({
        keyId: 1,
        product: "",
        triggerTypeList: [],
        conditionType: "expression",
        expression: "",
        conditionContentView: [
          {
            product: "",
            type: "",
            fun: "",
            condition: "",
            val: "",
            con: 'or'
          },
        ],
      });
      this.rulesForm.rules.forEach((item, index) => {
        item.keyId = index + 1;
      });
    },
    //删除告警规则
    deletePage(id) {
      const index = this.rulesForm.rules.findIndex((item) => item.keyId === id);
      if (index !== -1) this.rulesForm.rules.splice(index, 1);
    },
    deleteRule(index) {
      this.rulesForm.rules.splice(index, 1)
    },
    deleteAction(index) {
      this.inputData.splice(index, 1)
      this.actionForm.actionReqs.splice(index, 1)
    },
    //删除条件
    deleteCard(pageId, cardId) {
      const indexPage = this.rulesForm.rules.findIndex(
        (item) => item.keyId === pageId
      );
      const indexCard = this.rulesForm.rules[
        indexPage
      ].conditionContentView.findIndex((item) => item.cardId === cardId);
      this.rulesForm.rules[indexPage].conditionContentView.splice(indexCard, 1);
      // this.rulesForm.rules[indexPage].conditionContentView.forEach(
      //   (item, index) => {
      //     if ((index = length - 1)) {
      //       item.con = undefined;
      //     }
      //   }
      // );
    },
    //产品改变回调
    async productChange(data) {
      data.conditionContentView.forEach(item => {
        item.type = undefined
        this.triggerChange(item)
      })
      const product = this.productList.find(
        (product) => data.product === product.code
      );
      const productDataRes = await productDetail(product.id);
      if (productDataRes.data.metaData) {
        const productData = JSON.parse(productDataRes.data.metaData);
        //处理触发方式列表
        data.triggerTypeList = this.dealTriggerTypeList(productData);
      }
    },
    onConnect(num) {
      let len = this.rulesForm.rules[num].conditionContentView.length
      let lastCardId = this.rulesForm.rules[num].conditionContentView[len - 1].cardId
      this.rulesForm.rules[num].conditionContentView.push({
        cardId: lastCardId + 1,
        type: "",
        fun: "",
        condition: "",
        val: "",
        con: 'or'
      });
    },
    // 编辑规则确认操作
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loadingBtn = true
          editRulesContent(this.getParams).then((res) => {
            this.$message.success("编辑成功！");
            this.ruleId = res.data.ruleId
            this.getRulesData()
            this.loadingBtn = false
            this.rulesDialog = false;
          }).catch(err => {
            this.loadingBtn = false
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '~@/styles/antForm.scss';
@import '~@/styles/detailPage.scss';
.primary-info{
  .primary-info-item{
    width: 33.33%;
  }
}
.detailsList{
  padding-bottom: 16px;
  .rulesTitle{
    color: #999BA3;
    margin-bottom: 4px;
  }
}
.detailsWrap {
  .rulesTitle {
    display: inline-block;
    width: 120px;
  }
  .rulesCon {
    @include flexVC(space-between);
    cursor: pointer;
    margin: 16px 0 12px;
    .icon-desc{
      color: #2F54EB;
      margin-left: 4px;
    }
  }
  .rule-content{
    ul li{
      border: 1px solid #DCDEE0;
      border-bottom: none;
      border-radius: 4px;
      &:not(:first-child){
        margin-top: 16px;;
      }
    }
  }
  .tableTitle {
    border-bottom: 1px solid #DCDEE0;
    padding: 0 20px;
    margin: 0;
    background: #F7F8FA;
    line-height: 40px;
  }
  .tableList {
    margin: 0;
    line-height: 50px;
    border-bottom: 1px solid #DCDEE0;
    display: flex;
  }
  .tableItem {
    display: inline-block;
    width: 180px;
    flex-basis: 180px;
    flex-shrink: 0;
    text-align: center;
    border-right: 1px solid #DCDEE0;
  }
  .limit-condition{
    color: #999BA3;
  }
}
.timeDes {
  position: absolute;
  top: -30px;
  left: 80px;
  color: #FAAD14;
}
.notice-check{
  width: 100%;
  margin-top: 4px;
  .notice-item{
    background-color: #F7F8FA;
    padding: 10px 12px;
    border-radius: 4px;
    margin-bottom: 12px;
    .ant-radio-wrapper{
      display: flex;
      flex-direction: row-reverse;
      justify-content: space-between;
      align-items: center;
    }

    .check-label {
      @include flexVC(space-between);
    }
  }
  ::v-deep .ant-input, ::v-deep .ant-input-group{
    margin-top: 8px;
  }
  .expose-input ::v-deep  .ant-input {
    margin-top: 0;
  }
}
.hollow-btn{
  width: 100%;
}
.editDialog {
  ::v-deep .ant-checkbox-group {
    width: 100%;
  }
  .rulesWrap {
    border: 1px solid #DCDEE0;
    border-radius: 4px;
    padding: 0 12px 16px;
    margin-bottom: 12px;
    .page-title{
      padding: 8px 12px;
      margin: 0 -12px;
      background-color: #F7F8FA;
      @include flexVC(space-between);
    }
  }
  .rule-wrap{
    border-bottom: 1px solid #DCDEE0;
    &:not(:first-child){
      margin-top: 12px;
    }
  }
  .rulesList {
    position: relative;
    margin-left: - calc(10% / 3);
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .ant-form-item {
      margin-left: calc(10% / 3);
      width: 30%;
      ::v-deep .ant-radio-group {
        width: 100%;
      }
      ::v-deep .ant-radio-button-wrapper{
        border-radius: 4px;
        width: calc(50% - 8px);
        text-align: center;
        border: 1px solid #d9d9d9;
        &:not(:last-child) {
          margin-right: 8px;
        }
        &:not(:first-child)::before{
          content: none;
        }
      }
    }
    .delete-card:hover {
      color: #f60;
      cursor: pointer;
    }
  }
}
.add-rule{
  margin-top: 12px;
}
.condition-exp{
  background: #f2f3f7;
  border: 1px solid #dcdee0;
  margin-top: 12px;
  padding: 5px 12px;
  border-radius: 4px;
}
</style>
